#include "client.h"
#include <QDebug>

// Set up the client's socket
Client::Client(QTcpSocket* s)
{
    socket = s;
    size = 0;
    connect(socket, SIGNAL(readyRead()), this, SLOT(receiveMessage()), Qt::QueuedConnection);
}

// Receive a message across the socket
void Client::receiveMessage() {

    while (socket->bytesAvailable() > 0){

        QDataStream in(socket);
        in.setVersion(QDataStream::Qt_4_0);

        if (size == 0) {
            if (socket->bytesAvailable() < (int)sizeof(quint16))
                return;

            in >> size;
        }

        if (socket->bytesAvailable() < size)
            return;


        QString message;
        in >> message;
        size = 0;

        emit gotData(message);
    }
}

// Send a scheduleconflicts across the socket
void Client::sendConflicts(QString message) {
    QByteArray block;

    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);

    quint16 size = 0;
    out << size;
    out << (quint16)CONFLICT;
    out << message;

    size = (quint16) (block.size() - sizeof(quint16));
    out.device()->seek(0);
    out << size;

    socket->write(block);
}

// Send a population across the socket
void Client::sendPopulation(QString message) {
    QByteArray block;

    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);

    quint16 size = 0;
    out << size;
    out << (quint16)POPULATION;
    out << message;

    size = (quint16) (block.size() - sizeof(quint16));
    out.device()->seek(0);
    out << size;

    socket->write(block);
}

// Send a schedule across the socket
void Client::sendTimeSlots(QString message) {
    QByteArray block;

    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);

    quint16 size = 0;
    out << size;
    out << (quint16)TIMESLOTS;
    out << message;

    size = (quint16) (block.size() - sizeof(quint16));
    out.device()->seek(0);
    out << size;

    socket->write(block);
}
